package controller;

import core.UnZip;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.*;
import javafx.scene.text.TextFlow;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;

import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * 事件处理类
 *
 * @author xiaopu
 */
public class ButtonController implements Initializable {

    @FXML
    private Button sourceButton;
    @FXML
    private Button targetButton;
    @FXML
    private Button startButton;
    @FXML
    private TextField sourceField;
    @FXML
    private TextField targetField;
    @FXML
    private TextArea zipLog;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

    }

    public void setSourceField(ActionEvent event) {
        DirectoryChooser directoryChooser = new DirectoryChooser();
        directoryChooser.setTitle("选择源文件夹");
        File file = directoryChooser.showDialog(new Stage());
        String sourcePath = file.getAbsolutePath();
        sourceField.setText(sourcePath);

    }

    public void setTargetField(ActionEvent event) {
        DirectoryChooser directoryChooser = new DirectoryChooser();
        directoryChooser.setTitle("选择目标文件夹");
        File file = directoryChooser.showDialog(new Stage());
        String targetPath = file.getAbsolutePath();
        targetField.setText(targetPath);
    }

    public void startZip(ActionEvent event) throws Exception {
        String sourcePath = sourceField.getText();
        String targetPath = targetField.getText();
        if (!"".equalsIgnoreCase(sourcePath) && !"".equalsIgnoreCase(targetPath)) {
            ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
            singleThreadExecutor.execute(() -> {
                try {
                    new UnZip().unZipFile(sourcePath, targetPath, zipLog);
                    zipLog.appendText("解压完毕...");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }
}
